/**
 * <copyright> 
 *
 * Copyright (c) 2008 itemis AG and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors: 
 *   itemis AG - Initial API and implementation
 *
 * </copyright>
 *
 */
package com.rd.emf.geneditor.view.editors.generic.provider;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.provider.IItemLabelProvider;

import com.rd.emf.geneditor.model.OawFacade;
import com.rd.emf.geneditor.view.ImageRegistry;

/**
 * @author Dennis Huebner
 * 
 */
public class ExtendedLabelProvider implements IItemLabelProvider {

	private final OawFacade facade;

	public ExtendedLabelProvider(OawFacade facade) {
		this.facade = facade;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.emf.edit.provider.IItemLabelProvider#getImage(java.lang.Object
	 * )
	 */
	public Object getImage(Object element) {
		if (element instanceof EObject) {
			String platformString = ((EObject) element).eClass().eResource()
					.getURI().toPlatformString(true);
			if (platformString != null) {
				IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(
						new Path(platformString));
				if (file != null) {
					// probably jared
					String iconName = evaluate(element, "icon");
					if (iconName != null) {
						String imagePath = "/icons/"
								+ packageName((EObject) element) + "/"
								+ iconName;
						IFile f = file.getProject().getFile(imagePath);
						if (f != null) {
							// ask registry
							return ImageRegistry.getDefault().getImage(f);
						}
					}
				}
			}
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.emf.edit.provider.IItemLabelProvider#getText(java.lang.Object
	 * )
	 */
	public String getText(Object element) {
		String text = evaluate(element, "label");
		return text;
	}

	/**
	 * @param element
	 * @param retVal
	 * @return
	 */
	private String evaluate(Object element, String name) {
		String retVal = null;
		if (element instanceof EObject && facade != null) {
			EObject eO = (EObject) element;
			retVal = (String) facade.style(name, eO);
		}
		return retVal;
	}

	/**
	 * @param object
	 * @return
	 */
	private String packageName(EObject object) {
		return object.eClass().getEPackage().getName();
	}

}
